package com.test.demo.controller;

import com.test.demo.entity.Devices;
import com.test.demo.repository.DevicesRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;

import javax.persistence.criteria.CriteriaBuilder;
import java.util.List;

/**
 * @author: liangruichao
 * @date: 2022-08-20 22:23
 **/

@RestController
@CrossOrigin
@RequestMapping("/devices")
public class DevicesHandler {
    @Autowired
    private DevicesRepository devicesRepository;

    @GetMapping("/findAll/{page}/{size}")
    public Page<Devices> findAll(@PathVariable("page") Integer page, @PathVariable("size") Integer size) {
        Pageable pageable = PageRequest.of(page-1,size);
        return devicesRepository.findAll(pageable);
    }

    @PostMapping("/save")
    public String save(@RequestBody Devices devices){
        Devices result = devicesRepository.save(devices);
        if (result != null){
            return "success";
        }else {
            return "error";
        }
    }

    @GetMapping("/findByID/{id}")
    public Devices findByID(@PathVariable("id") Integer id) {
        return devicesRepository.findById(id).get();
    }

    @PutMapping("/update")
    public String update(@RequestBody Devices devices){
        Devices result = devicesRepository.save(devices);
        if (result != null) {
            return "success";
        }else {
            return "error";
        }
    }

    @DeleteMapping("/deleteById/{id}")
    public void deleteByID(@PathVariable("id") Integer id) {
        devicesRepository.deleteById(id);
    }
}
